package com.wjhs.redispractice.antishake.aspect;

import com.wjhs.redispractice.antishake.annotation.AntiShake;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.util.concurrent.TimeUnit;

@Aspect
public class AntiShakeAspect {
    private ThreadLocal<Long> lastInvokeTime = new ThreadLocal<>();

    @Around("@annotation(antiShake)")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint, AntiShake antiShake) throws Throwable {
        long currentTime = System.nanoTime();
        long lastTime = lastInvokeTime.get() != null ? lastInvokeTime.get() : 0;
        if (currentTime - lastTime < TimeUnit.NANOSECONDS.convert(antiShake.value(), TimeUnit.MILLISECONDS)) {
            // 如果距离上次调用时间小于指定的防抖时间，则直接返回，不执行方法
            return null; // 或者根据业务需要返回特定值
        }

        lastInvokeTime.set(currentTime);
        return joinPoint.proceed(); // 执行原方法
    }
}
